// pages/goTovideofabu/goTovideofabu.js
const db = wx.cloud.database()
let userInfo = {}
let contentbt = ''
let content = ''
let dianzan=''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    videoSrc:"",
    selectPhoto: true,
    biaoqian:0,
    contentjianche:true,
    contentjianchebt:true,
  },
  getzhuanti(){
    db.collection('zhuanti').where({
      biao:333
    }).get().then(res => {
      // 查询数据成功 
      this.setData({
        biaoqian1: res.data
      })
    }).catch(err => {
      // 查询数据失败
      console.log(err)
    })
  },
  biaoqian: function (e) {
    console.log(e.detail.value)
    this.setData({
      biaoqian: e.detail.value
    })
  },
  //选择视频
  chooseVideo: function () {
    var that =this
    wx.chooseVideo({
      sourceType: ['album','camera'],
      compressed: true,
      maxDuration: 60, //视频长度 单位 s
      camera: 'back',
      success(res) {
        
        that.setData({
          videoSrc: res.tempFilePath,
          img:res.thumbTempFilePath
        })
      }
      
    })
  },
// 删除视频
  onDelVideo: function () {
    this.setData({
      videoSrc: '',
    })
  },
  // 数据绑定
  content(event) {
    content = event.detail.value
    if(content!=''){ 
      wx.cloud.init();
      wx.cloud.callFunction({
        name: 'permissions',
        data: {
          content: content,
        }
      }).then(res => {
        console.log("内容安全审查结果：" + JSON.stringify(res));
        if (res.result.code == "200") { 
          this.setData({
            contentjianche:true
          })
        } else { //执行不通过
          this.setData({
            contentjianche:false
          })
          var v_content = res.result.msg;
          return wx.showModal({
            title: "提示",
            content: v_content,
            showCancel: false,
            confirmText: "确定",
          });
        }
      })}
  },
  onInputbt(event) {
    // console.log(event.detail.value)
    let wordsNum = event.detail.value.length
    if (wordsNum >= 20) {
      wordsNum = `最大字数为${20}`
    }
    contentbt = event.detail.value
    if(contentbt!=''){ 
      wx.cloud.init();
      wx.cloud.callFunction({
        name: 'permissions',
        data: {
          content: contentbt,
        }
      }).then(res => {
        console.log("内容安全审查结果：" + JSON.stringify(res));
        if (res.result.code == "200") { 
          this.setData({
            contentjianchebt:true
          })
        } else { //执行不通过
          this.setData({
            contentjianchebt:false
          })
          var v_content = res.result.msg;
          return wx.showModal({
            title: "提示",
            content: v_content,
            showCancel: false,
            confirmText: "确定",
          });
        }
      })}
  },
  // 点击发布 || this.data.videoSrc == '' 
  send() {
    if (contentbt.trim() === '' ||content.trim() === '' || this.data.images == ''||!this.data.contentjianche||!this.data.contentjianchebt|| this.data.videoSrc == '') {
      wx.showModal({
        title: '请完善内容',
        content: '',
      })
      return
    }

    wx.showLoading({
      title: '发布中',
      mask: true,
    })

    let promiseArr = []
    let fileIds = ''
    // 视频上传
      let p = new Promise((resolve, reject) => {
        let item = this.data.videoSrc
        // 文件扩展名
        let suffix = /\.\w+$/.exec(item)[0]
        wx.cloud.uploadFile({
          cloudPath: 'video/' + Date.now() + '-' + Math.random() * 1000000 + suffix,
          filePath: item,
          success: (res) => {
            console.log(res.fileID)
            fileIds = fileIds.concat(res.fileID)
            resolve()
          },
          fail: (err) => {
            console.error(err)
            reject()
          }
        })
      })
      promiseArr.push(p)
    
    // 存入到云数据库
    Promise.all(promiseArr).then((res) => {

      db.collection('shipin').add({
        data: {
          ...userInfo,
          content,
          contentbt,
          upNum:0,
          id:this.data.biaoqian1[this.data.biaoqian].id,
          biaoqian_ming:this.data.biaoqian1[this.data.biaoqian].content,
          dianzan,
          dz:0,
          ip:400,
          img:this.data.img,
          video: fileIds,
          createTime: db.serverDate(), // 服务端的时间
          biaoqian:parseInt(this.data.biaoqian),  
          opid:this.data.openid
        }
      }).then((res) => {
        wx.hideLoading()
           wx.showToast({
          title: '发布成功',
        })   
        wx.reLaunch({
          url: "/pages/index/shipin/shipin",
        })
      })
    }).catch((err) => {
      wx.hideLoading()
      wx.showToast({
        title: '发布失败',
      })
    })
    

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    userInfo = options
    this.getOpenid()
    this.getzhuanti()
  },
  getOpenid() {
    let that = this;
    wx.cloud.callFunction({
      name: 'getOpenid',
      complete: res => {
        console.log('云函数获取到的openid: ', res.result.openid)
        var openid = res.result.openid;
        that.setData({
          openid: openid
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})